var defaults = {
  d1 : { name: "tokyo", population: 10, area: 1, id: "d1"},
  d2 : { name: "kanagawa", population: 5, area: 1, id: "d2"},
  d3 : { name: "saitama", population: 4, area: 1, id: "d3"},
  d4 : { name: "chiba", population: 4, area: 1, id: "d4"}
};


var Store = function(name) {
  this.name = name;
  var store_ = localStorage[this.name];
  this.data = (store_ && JSON.parse(store_)) || defaults;
  if(this.data === defaults) this.save();
};

_.extend(Store.prototype, {
  save: function() {
    localStorage[this.name] = JSON.stringify(this.data);
  },

  create: function(model) {
    if(!model.id) model.id = _.uniqueId();
    this.data[model.id] = model;
    this.save();
    return model;
  },

  update: function(model) {
    this.data[model.id] = model;
    this.save();
    return model;
  },

  findAll: function(){
    return _.values(this.data);
  },

  destroy: function(model) {
    return model;
  }
});

Backbone.sync = function(method, model, success, error) {
  var resp, store = model.localStorage || model.collection.localStorage;

  switch(method) {
    case "read": resp = store.findAll(); break;
    case "create": resp = store.create(model); break;
    case "update": resp = store.update(model); break;
    case "delete": resp = store.destroy(model); break;
  }

  if(resp) {
    success(resp);
  } else {
    error("Record not found");
  }
};
